package memorphic.samplr.controllers
{
	import com.adobe.webapis.flickr.FlickrService;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import memorphic.samplr.ISamplrAppProps;
	import memorphic.samplr.SamplrStateManager;
	import memorphic.samplr.models.Gallery;
	import memorphic.samplr.models.PhotoSearchResults;
	import memorphic.samplr.models.SamplrPhoto;
	import memorphic.samplr.services.ServiceLocator;
	import memorphic.samplr.utils.TempPhotoCache;
	import memorphic.samplr.views.popups.StatusPopup;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	
	public class GalleryController
	{
		public static const GALLERIES_DIR:File = File.applicationStorageDirectory.resolvePath("Galleries");
		public static const NEW_GALLERY:Gallery = new Gallery("New gallery");
		
		private var view:ISamplrAppProps;
		private var galleries:ArrayCollection;
		private var statusPopup:StatusPopup;
		private var photoSearchResults:PhotoSearchResults;
		private var flickrDelegate:FlickrDelegate;
		
		public function GalleryController(rootView:ISamplrAppProps)
		{
			this.view = rootView;
			galleries = view.galleries;
			photoSearchResults = view.searchResults;
			init();
		}
		
		public function init():void
		{
			flickrDelegate = new FlickrDelegate();
			if (!GalleryController.GALLERIES_DIR.exists)
			{
				GalleryController.GALLERIES_DIR.createDirectory();
			}
			galleries.addItemAt(NEW_GALLERY,0);
			loadGalleries();
			getInterestingPics();
		}
		
		public function getInterestingPics():void
		{
			flickrDelegate.addEventListener(FlickrResultEvent.INTERESTINGNESS_GET_LIST, onGetInterestingPics);
			flickrDelegate.getInterestingPics();
		}
		
		private function onGetInterestingPics(evt:FlickrResultEvent):void
		{
			flickrDelegate.removeEventListener(FlickrResultEvent.INTERESTINGNESS_GET_LIST, onGetInterestingPics);
			view.interestingPhotos = evt.data.photos;
		}
		
		public function showGallery(gallery:Gallery):void
		{
			view.currentGallery = gallery;
			view.stateManager.stateURI = SamplrStateManager.GALLERY;
		}
		
		public function addGallery(gallery:Gallery):void
		{
			var newGalDir:File = GALLERIES_DIR.resolvePath(gallery.title);
			if (!newGalDir.exists)
			{
				newGalDir.createDirectory();
				gallery.url = newGalDir.url;
				galleries.addItem(gallery);
			}
			else
			{
				trace("Gallery with that title already exists.");
			}
		}
		
		public function getGalleryByTitle(title:String):Gallery
		{
			var len:int = galleries.length;
			for (var i:int = 0 ; i < len ; i++)
			{
				if (Gallery(galleries[i]).title == title)
				{
					return galleries[i];
				}
			}
			return null;
		}
		
		private function loadGalleries():void
		{
			for each (var dir:File in GALLERIES_DIR.getDirectoryListing())
			{
				if (dir.isDirectory)
				{
					var g:Gallery = new Gallery();
					g.title = dir.name;
					g.url = dir.url;
					g.photoList = loadGalleryPhotos(dir);
					galleries.addItem(g);
				}
			}
		}
		
		private function loadGalleryPhotos(dir:File):ArrayCollection
		{
			var ac:ArrayCollection = new ArrayCollection();
			for each (var file:File in dir.getDirectoryListing())
			{
				if (file.extension == "smp")
				{
					var fs:FileStream = new FileStream();
					fs.addEventListener(Event.COMPLETE,
						function onBufferComplete(evt:Event):void
						{
							var fstr:FileStream = FileStream(evt.target);
							var sp:SamplrPhoto = SamplrPhoto(fstr.readObject());
							fstr.close();
							ac.addItem(sp);
						}
					);
					fs.openAsync(file, FileMode.READ);
				}
			}
			return ac;
		}
		
		public function addSelectionToGallery(galleryTitle:String):void
		{
			statusPopup = new StatusPopup();
			statusPopup.statusText = "Please wait while the photos are saved to your gallery.";
			PopUpManager.addPopUp(statusPopup, view as DisplayObject,true);
			PopUpManager.centerPopUp(statusPopup);
			
			var len:int = view.selectedPhotos.length;
			var gallery:Gallery = getGalleryByTitle(galleryTitle);
			
			for (var i:int = 0 ; i < len ; i++)
			{
				var photo:SamplrPhoto = SamplrPhoto(ObjectUtil.copy(view.selectedPhotos.getItemAt(i)));
				savePhotoToGallery(photo, gallery);
				gallery.photoList.addItem(photo);
				photo.selected = false;
			}
			view.selectedPhotos = new ArrayCollection();
			showGallery(gallery);
		}
		
		private function savePhotoToGallery(photo:SamplrPhoto, gallery:Gallery):void
		{
			photo.parentGalleryTitle = gallery.title;
			flickrDelegate.addEventListener(FlickrResultEvent.PHOTOS_GET_SIZES, onGetSizes);
			flickrDelegate.getPhotoSizes(photo, gallery);
		}
		
		private function onGetSizes(evt:FlickrResultEvent):void
		{
			PopUpManager.removePopUp(statusPopup);
		}
		
		public function removeSelectionFromGallery():void
		{
			var galPhotos:ArrayCollection = view.currentGallery.photoList;
			var len:int = view.selectedPhotos.length;
			
			for (var i:int = 0 ; i < len ; i++)
			{
				var photo:SamplrPhoto = SamplrPhoto(view.selectedPhotos.getItemAt(i));
				deletePhotoFromGallery(photo);
				galPhotos.removeItemAt(galPhotos.getItemIndex(photo));
				photo.selected = false;
			}
			view.selectedPhotos = new ArrayCollection();
			showGallery(view.currentGallery);
		}
		
		private function deletePhotoFromGallery(photo:SamplrPhoto):void
		{
			var galleryDir:File = new File(view.currentGallery.url);
			var imageFile:File = galleryDir.resolvePath(photo.uniqueID + ".jpg");
			if (imageFile.exists) imageFile.deleteFileAsync();
			var samplrPhotoFile:File = galleryDir.resolvePath(photo.uniqueID + ".smp");
			if (samplrPhotoFile.exists) samplrPhotoFile.deleteFileAsync();
		}
		
		public function deleteGallery():void
		{
			var galleryDir:File = new File(view.currentGallery.url);
			galleryDir.deleteDirectoryAsync(true);
			view.galleries.removeItemAt(view.galleries.getItemIndex(view.currentGallery));
			view.currentGallery = null;
			view.stateManager.stateURI = SamplrStateManager.HOME;
		}
		
		private function onIOError(evt:IOErrorEvent):void
		{
			trace(evt.text);
		}
		
///////////////////////////////


		

		
		public function search(searchString:String):void
		{
			if (!photoSearchResults.pending)
			{
				photoSearchResults.pending = true;
				TempPhotoCache.clearCache();
				photoSearchResults.searchString = searchString;
				
				var service:FlickrService = ServiceLocator.getFlickrService();
				service.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
				if (searchString == "")
				{
					service.addEventListener(FlickrResultEvent.PHOTOS_GET_RECENT, onSearchResults);
					service.photos.getRecent();
				}
				else
				{
					service.addEventListener(FlickrResultEvent.PHOTOS_SEARCH, onSearchResults);
					service.photos.search("","","any",searchString);
				}
			}
		}
		
		private function onSearchResults(evt:FlickrResultEvent):void
		{
			FlickrService(evt.target).removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			if (evt.type == FlickrResultEvent.PHOTOS_SEARCH)
			{
				FlickrService(evt.target).removeEventListener(FlickrResultEvent.PHOTOS_SEARCH, onSearchResults);
			}
			else if (evt.type == FlickrResultEvent.PHOTOS_GET_RECENT)
			{
				FlickrService(evt.target).removeEventListener(FlickrResultEvent.PHOTOS_GET_RECENT, onSearchResults);
			}
			if (evt.success)
			{
//				photoSearchResults.results = pagedPhotoListToArrayCollection(PagedPhotoList(evt.data.photos));
				photoSearchResults.pending = false;
				view.stateManager.stateURI = SamplrStateManager.BROWSE;
			}
		}
		

		public function selectPhoto(photo:SamplrPhoto):void
		{
			if (photo.selected)
			{
				view.selectedPhotos.addItem(photo);
			}
			else
			{
				view.selectedPhotos.removeItemAt(view.selectedPhotos.getItemIndex(photo));
			}
		}
		
	
	}
}